package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.util.RSAUtils;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XinYongPaiRateUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 信用派-分润  双授权
 */
@Service
public class XinYongPaiSsqRatePushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String publicKey = pushApiKeyParam.getPubKey();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String apiKey = pushApiKeyParam.getApiKey();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("appamt", XinYongPaiRateUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("cityName", memberSourceInfo.getCity());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String createTime = format.format(date);
        bizMap.put("createTime", createTime);
        bizMap.put("custIp", XinYongPaiRateUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("custQualificationTag", XinYongPaiRateUtil.getZiZhi(memberSourceInfo.getHouse(),memberSourceInfo.getCar(),memberSourceInfo.getBaoxian(),
                memberSourceInfo.getGongzuo(),memberSourceInfo.getGjj(),memberSourceInfo.getShebao(),memberSourceInfo.getXinyongka(),
                memberSourceInfo.getBaitiao(),memberSourceInfo.getYuqi()));
        bizMap.put("domainFrom", apiKey);
        bizMap.put("name", SecureUtil.md5(memberSourceInfo.getRealname()));
        bizMap.put("phone", memberSourceInfo.getMobileMd5());
        bizMap.put("sesameSeed", XinYongPaiRateUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("sex", XinYongPaiRateUtil.getSex(memberSourceInfo.getSex()));


        //当前时间
        String time = String.valueOf(System.currentTimeMillis());
        String sign = this.encryptData(time,publicKey);


        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("x-ts", time);
        headerMap.put("x-sign", sign);
        headerMap.put("key", apiSecret);
        headerMap.put("Content-Type", "application/json");


        log.info("【信用派(分润)下游双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .headerMap(headerMap, true)
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);


        log.info("【信用派(分润)下游双授权】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (code == 0) {
            JSONObject jsonObject2 = resultObject.getJSONObject("data");
            Boolean needData = jsonObject2.getBoolean("needData");
            if (needData){
                pushApiResult.setCode(code + "|" + needData);
                JSONObject data = jsonObject2.getJSONObject("downStreamVO");

                String serialNo = UUID.randomUUID().toString();
                String downstreamAddress = data.getString("downstreamAddress");
                String logo = data.getString("downstreamLogPath");
                String name = data.getString("downstreamName");

                // 撞库成功之后，商户的机构数据存储

                ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
                thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
                thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
                thirdInfoDTO.setOrderNo(orderNo);
                JSONObject infoObject = new JSONObject();
                infoObject.put("orderNo", serialNo);
                infoObject.put("productId", serialNo);
                infoObject.put("productName", name);
                infoObject.put("companyName", name);
                infoObject.put("companyLogo", logo);
                infoObject.put("maxLoanAmount", "200000");
                infoObject.put("maxLoanRate", "7");
                infoObject.put("minLoanRate", "1");
                infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
                JSONArray jsonArray = new JSONArray();
                infoObject.put("protocalList", jsonArray);
                thirdInfoDTO.setInfoObject(infoObject);

                //进行分润操作
                String priceType = pushApiKeyParam.getPriceType();
                BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                    Integer unitPrice = data.getInteger("unitPrice");
                    BigDecimal price = new BigDecimal(unitPrice);//下游返回分润前价格
                    if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceRight = typeRate.multiply(price);//分润后价格
                    pushApiResult.setPrice(price);
                    pushApiResult.setPriceRight(priceRight);

                }

                boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
                if (save) {
                    pushApiResult.setPushSuccess(true);
                    pushApiResult.setOutOrderNo(serialNo);
                    extJson.put("serialNo", serialNo);
                } else {
                    pushApiResult.setMessage("保存撞库数据失败");
                }
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String serialNo = extJson.getString("serialNo");

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String publicKey = pushApiKeyParam.getPubKey();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String apiKey = pushApiKeyParam.getApiKey();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("appamt", XinYongPaiRateUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("cityName", memberSourceInfo.getCity());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String createTime = format.format(date);
        bizMap.put("createTime", createTime);
        bizMap.put("custIp", XinYongPaiRateUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("custQualificationTag", XinYongPaiRateUtil.getZiZhi(memberSourceInfo.getHouse(),memberSourceInfo.getCar(),memberSourceInfo.getBaoxian(),
                memberSourceInfo.getGongzuo(),memberSourceInfo.getGjj(),memberSourceInfo.getShebao(),memberSourceInfo.getXinyongka(),
                memberSourceInfo.getBaitiao(),memberSourceInfo.getYuqi()));
        bizMap.put("domainFrom", apiKey);
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("sesameSeed", XinYongPaiRateUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("sex", XinYongPaiRateUtil.getSex(memberSourceInfo.getSex()));


        String orderId = extJson.getString("orderId");
        String orderItemId = extJson.getString("orderItemId");
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(protocolUrl);
        bizMap.put("customerAuths", jsonArray);

        //当前时间
        String time = String.valueOf(System.currentTimeMillis());
        String sign = this.encryptData(time,publicKey);


        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("x-ts", time);
        headerMap.put("x-sign", sign);
        headerMap.put("key", apiSecret);
        headerMap.put("Content-Type", "application/json");

        log.info("【信用派(分润)下游双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .headerMap(headerMap, true)
                .body(JSON.toJSONString(bizMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【信用派(分润)下游双授权】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 0) {
            JSONObject data = resultObject.getJSONObject("data");
            String mcloudId = data.getString("mcloudId");
            pushApiResult.setCode(code + "|" + mcloudId);
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 0) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String encrypt(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key 为空 null");
            return null;
        }// 判断 Key 是否为 16 位
        if (sKey.length() != 16) {
            if (sKey.length() != 32) {
                System.out.print("Key 不合法");
                return null;
            }
        }
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); // 此处使用 BASE64 做转码功能，同时能起到 2 次加密的作用。
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String encryptData(String time, String publicKey) {
        Security.addProvider(new BouncyCastleProvider());
        RSAUtils rsaUtil = new RSAUtils();

        KeyFactory keyf = null;
        try {
            keyf = KeyFactory.getInstance("RSA", "BC");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey.getBytes()));
        //rsa加密(公Key)
        String sign = "";
        try {
            sign = rsaUtil.encryptData(time, keyf.generatePublic(pubX509));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }
}
